package com.small.utils;

import jdk.jfr.events.FileWriteEvent;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.sql.ResultSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author syd
 * @create 2020-12-13 9:23
 */
public class CsvUtil {

    private FileOutputStream file;
    private OutputStreamWriter out;
    private CSVPrinter csvPrinter;

    //文件分隔符
    private final static String NEW_LINE_SEPARATOR="\n";

    public boolean toWrite(String f, String[] headers, List<LinkedHashMap<Integer, String>> ml) throws Exception {

        try {

            file = new FileOutputStream(f);
            out = new OutputStreamWriter(file, "GBK");

            CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(headers).withTrim();
            csvPrinter = new CSVPrinter(out, csvFormat);

            //写入数据
            for (LinkedHashMap<Integer, String> m : ml) {
                /*for (String s : m.keySet()) {
                    csvPrinter.printRecord(s, m.get(s).toString());
                }*/
                csvPrinter.printRecord(m.values());
            }

            return true;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (!(csvPrinter ==null)) {
                csvPrinter.flush();
                csvPrinter.close();
            }
            if (!(out ==null)) {
                //out.flush();
                out.close();
            }
            if (!(file ==null)) {
                file.close();
            }
        }
    }
}
